<template>
	<div>
		<el-collapse :accordion="true" v-model="activeNames" @change="handleChange">
      <el-collapse-item title="评估基础信息" name="baseInfo">
        <AplidForm ref="formRef" v-bind="baseInfoConfig" v-model="baseInfoModel" @reset="refresh" @submit="onSubmit"></AplidForm>
      </el-collapse-item>
			<el-collapse-item v-for="(item, index) in tableNameList" :key="index" :title="item.tableTitle" :name="item.id">
				<AplidForm :key="configChange" ref="formRef" v-bind="config" v-model="formModel"></AplidForm>
			</el-collapse-item>
		</el-collapse>
    <div class="submit_row">
      <div class="submit_btn">
        <el-button type="primary" @click="toSubmit">提交，计算分数</el-button>
        <el-button @click="toBack">返回</el-button>
      </div>
    </div>
	</div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
// import {formConfig} from '../../config'
import apiMod from '@/apiMod/index'
import {getAreaObj} from '@/utils/util'
import * as _ from 'lodash-es'
type Props = {
  nowRowData?:any
}
let props = withDefaults(defineProps<Props>(),{
  nowRowData:{}
})
let emit = defineEmits(['refresh'])

const toSubmit = () =>{
  apiMod.view_bscElderlyAssessBaseInfo_calc({taskId:props.nowRowData.taskId,taskItemId:props.nowRowData.taskItemId,idCard:props.nowRowData.idCard}).then(res=>{
    if(res.code == 0){
      ElMessage.success('提交成功')
      toBack()
    }
  })
}
const toBack = () =>{
  emit('refresh')
}
let baseInfoModel = ref({})
// 获取基础信息
const getBaseInfo = () =>{
  apiMod.view_bscElderlyAssessBaseInfo_page({assessCode:props.nowRowData.assessCode}).then(res=>{
    if(res.code == 0){
      baseInfoModel.value = res.data.records[0]
      baseInfoModel.value['cr_area'] = getAreaObj(baseInfoModel.value,'cr','set')['areaIds']
      baseInfoModel.value['cr_area_name'] = getAreaObj(baseInfoModel.value,'cr','set')['names']
    }
  })
}
getBaseInfo()
// 基础信息配置
let baseInfoConfig = {
  inline:false,
  showBtn:true,
  labelWidth:'180px',
  column:[
  {
			type: 'DividerHtml',
			modelValue: '评估信息表',
			labelPosition: 'top',
			position: 'center',
			span: 24,
		},
    // {label:'评估编号',prop:'assessCode',type:'input',span:24},
    {
      label:'评估时间',
      format:'YYYY年MM月DD日',
      valueFormat:'YYYY-MM-DD',
      prop:'assessDate',
      type:'date',
      span:24},
      {
        label:"评估地点",
        prop:"assessAddress",
        span:24
      },
    {
      label:'评估原因',
      prop:'assessReason',
      propName:'assessReasonLabel',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'ASSESS_REASON',
      span:24
    },
    {label:'其他评估原因',prop:'assessReasonOther',type:'input',span:24},
    {
			type: 'DividerHtml',
			modelValue: '评估对象基本信息表',
			labelPosition: 'top',
			position: 'center',
			span: 24,
		},
    {label:'身份证号',prop:'idCard',type:'input',span:24},
    {label:'老人姓名',prop:'oldmanName',type:'input',span:24},
    {
      label:'老人性别',
      prop:'gender',
      propName:"genderLabel",
      type:'remoteSelect',
      code:"GENDER",
      api:"getDictItemList",
      span:24
    },
    {label:'老人照片',prop:'oldmanPhotoOne',type:'upload',span:24,limit:1},
    {label:'老人持证照片',prop:'oldmanPhotoTwo',type:'upload',limit:1,span:24},
    {label:'老人联系方式',prop:'oldmanPhone',type:'input',limit:1,span:24},
    {label:'所属区域',prop:'cr_area',propName:'cr_area_name',type:'AplidAreaSelect',span:24},
    {label:'详细地址',prop:'address',type:'input',span:24},
    {label:'身高(CM)',prop:'oldmanHeight',type:'input',span:24},
    {label:'体重(KG)',prop:'oldmanWeight',type:'input',span:24},
    {
      label:'民族',
      prop:'nationType',
      propName:'nationTypeLabel',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'NATIONALITY',
      span:24},
    {
      label:'宗教信仰',
      prop:'faithType',
      propName:'faithTypeLabel',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'RELIGIOUS_BELIEF',
      span:24
    },
    {
      label:'文化程度',
      prop:'eduType',
      propName:'eduTypeLabel',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'EDUCATION_DEGREE',
      span:24
    },
    {
      label:'居住情况',
      prop:'livingType',
      propName:'livingTypeLabels',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'LIVE_SITUATE',
      multiple:true,
      span:24
    },
    {
      label:'婚姻状况',
      prop:'marriage',
      propName:'marriageLabel',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'MARITAL_STATUS',
      span:24
    },
    {
      label:'医疗费用支付方式(多选)',
      prop:'payWay',
      propName:'payWayLabels',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'MEDICAL_PAY_WAY',
      multiple:true,
      span:24
    },
    {
      label:'经济来源(多选)',
      prop:'economicSource',
      propName:'economicSourceLabels',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'INCOME_SOURCE',
      multiple:true,
      span:24
    },
    {
			type: 'DividerHtml',
			modelValue: '近30天内照护风险事件',
			labelPosition: 'top',
			position: 'center',
			span: 24,
		},
    {
      label:'跌倒',
      prop:'fall',
      propName:'fallLabel',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'NURSE_RISK',
      span:24
    },
    {
      label:'走失',
      prop:'lost',
      propName:'lostLabel',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'NURSE_RISK',
      span:24
    },
    {
      label:'噎食',
      prop:'choking',
      propName:'chokingLabel',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'NURSE_RISK',
      span:24
    },
    {
      label:'自杀、自伤',
      prop:'suicide',
      propName:'suicideLabel',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'NURSE_RISK',
      span:24
    },
    {
      label:'其他',
      prop:'other',
      propName:'otherLabel',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'NURSE_RISK',
      span:24
    },
    
    {
			type: 'DividerHtml',
			modelValue: '信息提供者及联系人信息表',
			labelPosition: 'top',
			position: 'center',
			span: 24,
		},
    {label:'信息提供者的姓名',prop:'provideName',type:'input',span:24},
    {
      label:'信息提供者与老年人的关系',
      prop:'provideRelation',
      propName:'provideRelationLabel',
      type:'remoteSelect',
      api:'getDictItemList',
      code:'ELDERLY_RELATIONSHIP',
      span:24
    },
    {label:'联系人姓名',prop:'contactsName',type:'input',span:24},
    {label:'联系人电话',prop:'contactsPhone',type:'input',span:24},
  ]
}

let formModel = ref({})


let activeNames = ref(1)
const handleChange = () => {}
const onSubmit = (form, done) => {
    // 处理数据
    let crAreaObj = getAreaObj(form.cr_area,'cr')
    let crAreaNameObj = getAreaObj(form.cr_area_name,'cr')
    let params = {
      ...form,
      cr_area:undefined,
      cr_area_name:undefined,
      ...crAreaObj,
      ...crAreaNameObj
    }
    apiMod.view_bscElderlyAssessBaseInfo_edit(params).then(res=>{
      done()
      console.log('修改',res)
    })
}
let formRef = ref()
const refresh = () =>{
    emit('refresh')
  }
  const onSave = () => {
    formRef.value!.onSubmit()
  }
  // 获取表名称
  let tableNameList = ref([])
  const getTableName = () => {
    apiMod.view_bscAssessTableInfo_list({assessType:1}).then(res=>{
      tableNameList.value = res.data
    })
  }
  getTableName()
  let configChange = ref(1)
  // 监听打开的折叠面板
  let tableItem = ref({})
  let config:any = ref({
    inline:false,
    showBtn:false,
    column:[]
  })
  // 是否要进行算分
  let scoreEnable = ref(0)
  // 答案数据
  watch(activeNames,(newVal:any)=>{
    if(newVal && newVal!='baseInfo'){
      let table = tableNameList.value.find(el=>{
        return el.id == newVal
      })
      
      scoreEnable.value = table.scoreEnable
      apiMod.view_bscAssessTableItem_page({assessType:1,tableId:newVal,taskId:props.nowRowData.taskId,taskItemId:props.nowRowData.taskItemId,pageParaPO:{size:100000,current:1}}).then(res=>{
        config.value.column = []
        res.data.records.forEach(el=>{
          // 判断类型，转成config配置
          if(el.itemType ==1){
            let obj = []
            if(el.optionList){
              obj  =  el.optionList.map(dict=>{
                return {label:dict.optionContent,value:dict.id}
              })
            }
            config.value.column.push({label:el.itemTitle,prop:el.id,type:'radio',dicData:obj,labelPosition:'left',span:24,onChange:(e)=>editAnswer(e,el)
          })
          formModel.value[el.id] = el.bscAssessTableAnswer?el.bscAssessTableAnswer.content:''
          }
          // 如果是多选
          if(el.itemType ==2){
            let obj = []
            if(el.optionList){
              obj  =  el.optionList.map(dict=>{
                return {label:dict.optionContent,value:dict.id}
              })
            }
            config.value.column.push({label:el.itemTitle,prop:el.id,type:'checkbox',dicData:obj,labelPosition:'left',span:24,onChange:(e)=>editAnswer(e,el)
          })
          formModel.value[el.id] = el.bscAssessTableAnswer?el.bscAssessTableAnswer.content.split(","):[]
          }
          // 填空
          if(el.itemType == 3){
            config.value.column.push({label:el.itemTitle,prop:el.id,type:'input',labelPosition:'left',span:24,onChange:(e)=>editAnswer(e,el)
          })
          formModel.value[el.id] = el.bscAssessTableAnswer?el.bscAssessTableAnswer.content:''
          }
          if(el.itemType ==4){
            let subColumn  =  el.optionList.map(sub=>{
                return {label:sub.optionContent,prop:sub.id,span:6,type:'input'}
            })
            config.value.column.push({label:el.itemTitle,prop:el.id,type:'dynamic',addBtn:false,delBtn:false,column:subColumn,span:24,rowChange:(e,_,data)=>editAnswer(e,el,data)
          })
          let handleData = JSON.parse(el.bscAssessTableAnswer.content)
          // const a = Object.entries(handleData).map(([key,values]) => {
          //   const arr = values.map(item => {
          //   return {
          //     [key]: item
          //   }
          //  })
          //   return arr
          // })
          let keysList = Object.keys(handleData)
          let list2 = []
          
          // console.log('jihe',jihe)
          let list1 = new Array(el.lineNumber)
          list1.fill("")
          list1.forEach((a,i)=>{
            let jihe = {}
            keysList.forEach(item=>{
              jihe[item] = handleData[item][i]
            })
            list2.push(jihe)
          })
          formModel.value[el.id] = list2
          }
        })
        tableItem.value = res.data.records
        configChange.value = Math.random()
      })
    }
  })
  	// 修改答案
	const editAnswer = (e:any, item,data?) => {
    
		let params:any = {
			scoreEnable:scoreEnable.value,
			assessCode:props.nowRowData.assessCode,
			assessType: 1,//1表示是老年人能力评估
			itemId: item.id,
      taskId:props.nowRowData.taskId,
      taskItemId:props.nowRowData.taskItemId,
			tableId: item.tableId,
		}
		if(item.itemType ==2){
      let obj = item.optionList.find(el=>{
        return e.includes(el.id)
      })
			params = {
				...params,
				content: e.join(','),
        answerType:obj.optionType,
				answerScore: scoreEnable.value==1 ?obj.optionScore:undefined
			}
		}else if(item.itemType ==1){
      let obj = item.optionList.find(el=>{
        return el.id == e
      })
			params = {
				...params,
				content: e,
        answerType:obj.optionType,
				answerScore: scoreEnable.value==1 ?obj.optionScore:undefined
			}
		}else if(item.itemType ==4){
      console.log('什么样子',JSON.parse(item.bscAssessTableAnswer.content))
      // 处理答案
      // const ad = Object.keys(data[0]).map(key => {
      //   const obj = {}
      //   const values = data.map(item => {
      //     return item[key]
      //   })
      //   obj[key] = values?values:''
      //   return obj
      // })
      console.log('-0-0-',data)
      let ad = {}
      
      if(data){
        let copyData =JSON.parse(JSON.stringify(data))
        let keyList = Object.keys(copyData[0])
        
          keyList.forEach(a=>{
            let list = []
            copyData.forEach(el=>{
              list.push(el[a])
            })
            ad[a] = list
          })
      }
			params = {
				...params,
        content:JSON.stringify(ad),
        answerType:4,
				answerScore: 0,
			}
      console.log('dsdsd',params)
		}else if(item.itemType ==3){
      params = {
				...params,
				content: e,
        answerType:3
			}
    }
    // 编辑
    apiMod.view_bscAssessTableAnswer_addOrUpdate(params).then(res=>{

    })
	}
  defineExpose({
    onSave
  })
</script>
<style scoped lang="scss">
.submit_row{
  margin-top: 40px;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}
.submit_btn{
  width: 30%;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
}
</style>
